package com.love_weinuo.ui.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;

import com.lzy.okgo.callback.StringCallback;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendGenderType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.qcloud.uikit.common.utils.ImageUtil;
import com.love_weinuo.R;
import com.love_weinuo.bean.LoginCallbackBean;
import com.love_weinuo.bean.UpdataImageCallbean;
import com.love_weinuo.bean.UserInfoCallBack;
import com.love_weinuo.databinding.ActivityMyInfoBinding;
import com.love_weinuo.ui.BaseActivity;
import com.love_weinuo.util.BHThreadPool;
import com.love_weinuo.util.GsonUtil;
import com.love_weinuo.util.HTTPAPI;
import com.love_weinuo.util.ImageUtils;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.PermissionUtil;
import com.love_weinuo.util.SpUtils;
import com.love_weinuo.util.ToastUtil;
import com.love_weinuo.util.dialog.InCommonDialog;
import com.love_weinuo.util.dialog.PhotoDialog;
import com.love_weinuo.util.glideutil.GlideUtil;
import com.love_weinuo.util.listener.OnBHClickListener;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.love_weinuo.bean.Constants.BASE_RES_HEAD_URL;
import static com.love_weinuo.bean.Constants.LOGINPRESSION;
import static com.love_weinuo.bean.Constants.REQUEST_CODE_LOCATION;

/**
 * Created by SensYang on 2019/03/01 13:05
 * sex:
 * 0 男
 * 1 女
 */

public class MyInfoActivity extends BaseActivity {

    ActivityMyInfoBinding binding;
    List<File> files = new ArrayList<>();
    Uri uri;
    String capath, name, head;
    String sex = "0";
    String userId = (String) SpUtils.get("module_user_id", "");
    LoginCallbackBean.ResultEntity.ResEntity userBean = (LoginCallbackBean.ResultEntity.ResEntity) SpUtils.getBean("module_user_bean");
    String nickName = (String) SpUtils.get("module_user_nickname", "");
    String UserSex = (String) SpUtils.get("module_user_sex", "");

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_my_info);
        binding.setActivity(this);
        initView();
    }

    private void initView() {
        getReasionAllInfo();
        add(this);
        setBack();
        setTitleText("我的信息");
        binding.setBean(userBean);
        binding.tvModuleName.setText(nickName);
        try {
            if ("0".equals(UserSex)) {
                binding.tvModuleMan.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_man));
                binding.tvModuleWoman.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_woman));
            } else if ("1".equals(UserSex)) {
                binding.tvModuleMan.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_man_noselect));
                binding.tvModuleWoman.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_woman_select));
            }
        } catch (Exception e) {
            LogUtil.e("userBean解析失败");
        }


        binding.tvModuleMan.setOnClickListener(this);
        binding.tvModuleWoman.setOnClickListener(this);
        binding.llModuleChangeNickName.setOnClickListener(this);
        binding.llModuleChangepwd.setOnClickListener(this);
        binding.ivModuleHead.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvModuleMan:
                binding.tvModuleMan.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_man));
                binding.tvModuleWoman.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_woman));
                sex = "0";
                updataSex(sex);
                break;
            case R.id.tvModuleWoman:
                binding.tvModuleMan.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_man_noselect));
                binding.tvModuleWoman.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_woman_select));
                sex = "1";
                updataSex(sex);
                break;
            case R.id.llModuleChangeNickName:
                startActivity(new Intent(MyInfoActivity.this, ChangeNickNameActivity.class));
                break;
            case R.id.llModuleChangepwd:
                startActivity(new Intent(MyInfoActivity.this, ForgetActivity.class)
                        .putExtra("fromStyle", "change"));
                break;
            case R.id.ivModuleHead:
                PhotoDialog dialog = new PhotoDialog(this);
                dialog.show();
                dialog.setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        photoPoint();
                    }

                    @Override
                    public void onCloseClick() {
                        photoAlbum();
                    }
                });
                break;
            default:
        }
    }

    public void photoPoint() {
        if (PermissionUtil.cameraPermission(this, LOGINPRESSION)) {
            uri = ImageUtils.createImagePathUri(this);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, 0);
        }
    }

    public void photoAlbum() {
        if (PermissionUtil.cameraPermission(this, REQUEST_CODE_LOCATION)) {
            Intent intent = new Intent("android.intent.action.PICK");
            intent.setType("image/*");
            startActivityForResult(intent, 3);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOGINPRESSION:
                if (PermissionUtil.loginPermission(this, LOGINPRESSION)) {
                    photoPoint();
                } else {
                    ToastUtil.showToast("请允许相关权限");
                    return;
                }
                break;
            case REQUEST_CODE_LOCATION:
                if (PermissionUtil.loginPermission(this, REQUEST_CODE_LOCATION)) {
                    photoAlbum();
                } else {
                    ToastUtil.showToast("请允许相关权限");
                    return;
                }
                break;
            default:
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 0) {
                capath = uri + "";
                if ((capath + "").contains("content")) {
                    capath = ImageUtils.getRealPathFromURI(this, uri);
                } else if (capath.contains("file:///")) {
                    capath = capath.substring(7, capath.length());
                } else {
                    capath = data.getData().toString();
                }
                GlideUtil.setCircleMethod(MyInfoActivity.this, capath, binding.ivModuleHead);
                lubanMethod(capath);
            } else if (requestCode == 3) {
                if (data == null) {
                    return;
                }
                capath = ImageUtils.getInstance().getFilePathMethod(this, data.getData());
                GlideUtil.setCircleMethod(MyInfoActivity.this, capath, binding.ivModuleHead);
                lubanMethod(capath);
            }
        }
    }

    public void lubanMethod(final String str) {
        Luban.with(this).
                load(new File(str)).
                setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        files.clear();
                    }

                    @Override
                    public void onSuccess(File file) {
                        files.add(file);
                        final Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                HTTPAPI.getInstance().updataHeadImg(userId, files,
                                        new StringCallback() {
                                            @Override
                                            public void onSuccess(String s, Call call, Response response) {
                                                LogUtil.e("个人头像上传成功" + s);
                                                UpdataImageCallbean bean = GsonUtil.GsonToBean(s, UpdataImageCallbean.class);
                                                head = bean.getResult();
                                                setFaceMethod(name, head);
                                            }

                                            @Override
                                            public void onError(Call call, Response response, Exception e) {
                                                LogUtil.e("个人头像上传失败" + e.getMessage());
                                            }
                                        });
                            }
                        };
                        BHThreadPool.getInstance().executeTask(runnable);
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.e("鲁班压缩出错");
                    }
                }).launch();
    }

    public void updataSex(final String sex) {
        InCommonDialog dialog = new InCommonDialog(this);
        if ("0".equals(sex)) {
            dialog.setTitleText("性别更改为男？");
        } else if ("1".equals(sex)) {
            dialog.setTitleText("性别更改为女");
        }
        dialog.show();
        dialog.setOnBHClickListener(new OnBHClickListener() {
            @Override
            public void onConfirmClick() {
                HTTPAPI.getInstance().updataSex(userId, sex, new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LogUtil.e("更新性别成功" + s);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        LogUtil.e("更新性别失败" + e.getMessage());
                    }
                });
            }

            @Override
            public void onCloseClick() {

            }
        });
    }

    public void getReasionAllInfo() {
        HTTPAPI.getInstance().getUserInfo(userId, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("获取个人信息成功" + s);
                UserInfoCallBack bean = GsonUtil.GsonToBean(s, UserInfoCallBack.class);
                switch (bean.getErrcode()) {
                    case 0:
                        GlideUtil.setCircleMethod(MyInfoActivity.this, bean.getResult().getHeadimg(), binding.ivModuleHead);
                        if (0 == bean.getResult().getSex()) {
                            binding.tvModuleMan.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_man));
                            binding.tvModuleWoman.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_woman));
                        } else if (1 == bean.getResult().getSex()) {
                            binding.tvModuleMan.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_man_noselect));
                            binding.tvModuleWoman.setBackground(getResources().getDrawable(R.drawable.draw_activity_myinfo_sex_woman_select));
                        }
                        binding.tvModuleName.setText(bean.getResult().getNickname());
                        binding.tvModulePhone.setText(bean.getResult().getMobile());
                        break;
                    default:
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("获取个人信息失败" + e.getMessage());
            }
        });
    }

    public void setFaceMethod(String name, String img) {
        HashMap<String, Object> profileMap = new HashMap<>();
        profileMap.put(TIMFriendshipManager.TIM_PROFILE_TYPE_KEY_NICK, name);
        profileMap.put(TIMFriendshipManager.TIM_PROFILE_TYPE_KEY_GENDER, TIMFriendGenderType.Male.value());
        profileMap.put(TIMFriendshipManager.TIM_PROFILE_TYPE_KEY_FACEURL, img);
        TIMFriendshipManager.getInstance().modifySelfProfile(profileMap, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                LogUtil.e(code + "设置失败" + desc);
            }

            @Override
            public void onSuccess() {
                ToastUtil.showToast("头像上传成功");
                LogUtil.e("设置成功");
                finish();
            }
        });
    }

}
